package com.network.service.impl;

import com.network.mapper.UserInfoMapper;
import com.network.mapper.UserMapper;
import com.network.mapper.UserRelationMapper;
import com.network.pojo.User;
import com.network.pojo.UserInfo;
import com.network.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    UserRelationMapper userRelationMapper;

    @Override
    public List<User> getAllUser(Date date) {
        List<User> allUser = userMapper.getAllUser(date);
        allUser.forEach((e)->{e.getUserInfo();});

        return allUser;
    }

    @Override
    public UserInfo login(String username, String password) {
        return userRelationMapper.findUserInfo(username, password);
    }


    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
    @Override
    public void register(User user,String picture,boolean chicken) {
        userMapper.insertUser(user);


//        System.out.println(user);
        userInfoMapper.insertUserInfo(user.getId());



        UserInfo userInf = userRelationMapper.finUserInfoByUsername(user.getUsername());

//        System.out.println(userInf);

        if (picture != null) {
            UserInfo userInfo = new UserInfo();
            userInfo.setPicture(picture);
            userInfo.setId(userInf.getId());
            userInfo.setChicken(chicken);
//            System.out.println(userInfo);
            userInfoMapper.updateUserInfo(userInfo);
        }




    }


    @Override
    public void updateUserByUsername(String username, String password) {
        userMapper.updateUserByUsername(username,password);
    }

    @Override
    public User checkUsername(String username) {
        return userMapper.findUserByUsername(username);
    }

    @Override
    public void updatePassword(int id, String password) {
        userMapper.updateUser(id, password);
    }

    @Override
    public void deleteUser(int id) {
        userMapper.deleteUser(id);
    }

    @Override
    public void deleteUserByUsername(String username) {
        userMapper.deleteUserByUsername(username);
    }
}
